package com.ruoyi.sales.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.entity.ZcProcess;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.sales.mapper.ZcProcessMapper;
import com.ruoyi.sales.service.IZcProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ZcProcessServiceImpl implements IZcProcessService {

    @Autowired
    private ZcProcessMapper processMapper;

    @Override
    @DataScope(processAlias = "p")
    public List<ZcProcess> selectProcessList(ZcProcess process) {
        return processMapper.selectProcessList(process);
    }

    @Override
    public ZcProcess selectProcessById(Long processId) {
        return processMapper.selectProcessById(processId);
    }

    @Override
    public boolean checkProcessNameUnique(ZcProcess process) {
        Long processId = StringUtils.isNull(process.getProcessId()) ? -1L : process.getProcessId();
        ZcProcess info = processMapper.checkProcessNameUnique(process.getProcessName(), process.getParentId());
        if (StringUtils.isNotNull(info) && info.getProcessId().longValue() != processId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int insertProcess(ZcProcess process) {
        ZcProcess info = processMapper.selectProcessById(process.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("类别工序停用，不允许新增");
        }
        process.setAncestors(info.getAncestors() + "," + process.getParentId());
        return processMapper.insertProcess(process);
    }

    @Override
    public int selectNormalChildrenProcessById(Long processId) {
        return processMapper.selectNormalChildrenProcessById(processId);
    }

    @Override
    public int updateProcess(ZcProcess process) {
        ZcProcess newParentStock = processMapper.selectProcessById(process.getParentId());
        ZcProcess oldDept = processMapper.selectProcessById(process.getProcessId());
        if (StringUtils.isNotNull(newParentStock) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentStock.getAncestors() + "," + newParentStock.getProcessId();
            String oldAncestors = oldDept.getAncestors();
            process.setAncestors(newAncestors);
            updateProcessChildren(process.getProcessId(), newAncestors, oldAncestors);
        }
        int result = processMapper.updateProcess(process);
        if (UserConstants.DEPT_NORMAL.equals(process.getStatus()) && StringUtils.isNotEmpty(process.getAncestors())
                && !StringUtils.equals("0", process.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentProcessStatusNormal(process);
        }
        return result;
    }

    @Override
    public boolean hasChildByProcessId(Long processId) {
        int result = processMapper.hasChildByProcessId(processId);
        return result > 0;
    }

    @Override
    public int deleteProcessById(Long processId) {
        return processMapper.deleteProcessById(processId);
    }

    @Override
    public List<TreeSelect> selectProcessTreeList(ZcProcess process) {
        List<ZcProcess> processes = SpringUtils.getAopProxy(this).selectProcessList(process);
        return buildProcessTreeSelect(processes);
    }

    @Override
    public List<ZcProcess> buildProcessTree(List<ZcProcess> processes) {
        List<ZcProcess> returnList = new ArrayList<ZcProcess>();
        //processes.stream() 将输入的 processes 列表转换成一个流（Stream）
        //.map(ZcProcess::getProcessId) 使用map操作对流中的每个processId应用一个函数 返回一个新的流
        //.collect(Collectors.toList()) 使用 collect 操作将流中的元素收集到一个新的列表中 会创建一个新的列表，并将流中的元素添加到这个列表中
        //tempList 包含processes内的每个processId的列表 用于后续的顶级节点检查
        List<Long> tempList = processes.stream().map(ZcProcess::getProcessId).collect(Collectors.toList());
        for (ZcProcess process : processes)
        {
            //tempList被用来检查一个 ZcProcess 对象是否是一个顶级节点
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(process.getParentId()))
            {
                //recursionFn 递归
                recursionFn(processes, process);
                //并将顶级节点添加到 returnList 中
                returnList.add(process);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = processes;
        }
        return returnList;
    }

    private void recursionFn(List<ZcProcess> list, ZcProcess t) {
        // 得到子节点列表
        List<ZcProcess> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ZcProcess tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    private boolean hasChild(List<ZcProcess> list, ZcProcess t) {
        return getChildList(list, t).size() > 0;
    }

    private List<ZcProcess> getChildList(List<ZcProcess> list, ZcProcess t) {
        List<ZcProcess> tlist = new ArrayList<>();
        Iterator<ZcProcess> it = list.iterator();
        while (it.hasNext())
        {
            ZcProcess n = (ZcProcess) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getProcessId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    @Override
    public List<TreeSelect> buildProcessTreeSelect(List<ZcProcess> processes) {
        List<ZcProcess> processTrees = buildProcessTree(processes);
        return processTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public int updateProcessStatus(ZcProcess process) {
        return processMapper.updateProcessStatus(process);
    }


    private void updateParentProcessStatusNormal(ZcProcess process) {
        String ancestors = process.getAncestors();
        Long[] stockIds = Convert.toLongArray(ancestors);
        processMapper.updateProcessStatusNormal(stockIds);
    }

    private void updateProcessChildren(Long processId, String newAncestors, String oldAncestors) {
        List<ZcProcess> children = processMapper.selectChildrenProcessById(processId);
        for (ZcProcess child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            processMapper.updateProcessChildren(children);
        }
    }
}
